package br.com.games.daedal.ui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;

public class Edge {

	private int scale, offset;
	private boolean selected = false;
	private boolean marked   = false;
	private int[] l = new int[16];
	private Color color;
	
	public static Stroke STROKE = new BasicStroke(4);

	public Edge(int[] local, int offset, int scale) {
		int w = 3;
		if (local[1] == local[3]) {
			l[8 ] = l[0] = (local[0]*scale+offset);
			l[9 ] = l[1] = (local[1]*scale+offset) + w;
			l[12] = l[2] = (local[0]*scale+offset);
			l[13] = l[3] = (local[1]*scale+offset) - w;			
			l[10] = l[4] = (local[2]*scale+offset);
			l[11] = l[5] = (local[3]*scale+offset) + w;
			l[14] = l[6] = (local[2]*scale+offset);
			l[15] = l[7] = (local[3]*scale+offset) - w;			
		} else {
			l[8 ] = l[0] = (local[0]*scale+offset) + w;
			l[9 ] = l[1] = (local[1]*scale+offset);
			l[12] = l[2] = (local[0]*scale+offset) - w;
			l[13] = l[3] = (local[1]*scale+offset);				
			l[10] = l[4] = (local[2]*scale+offset) + w;
			l[11] = l[5] = (local[3]*scale+offset);
			l[14] = l[6] = (local[2]*scale+offset) - w;
			l[15] = l[7] = (local[3]*scale+offset);	
		}
	}
	
	public boolean isInside(int x, int y){
		
		boolean result = false;
		int sx=Integer.MAX_VALUE, lx = -1; 
		
		for (int i = 0; i < 16; i+=2){
			if (sx > l[i]) sx = l[i];
			if (lx < l[i]) lx = l[i];
		}
		
		if ((x >= sx) && (x <= lx)){
			sx=Integer.MAX_VALUE;
			lx = -1; 
			for (int i = 1; i < 16; i+=2){
				if (sx > l[i]) sx = l[i];
				if (lx < l[i]) lx = l[i];
			}	
			result = (y >= sx) && (y <= lx);
		}
		
		return result;
	}

	public void setSelected(boolean selected, Color color) {
		this.selected = selected;
		this.color    = color;
	}

	public void paint(Graphics g) {
		if (selected) {
			Graphics2D g2 = (Graphics2D) g;
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				                RenderingHints.VALUE_ANTIALIAS_ON);
			g2.setStroke(STROKE);
			g2.setColor(this.color);
 
			for (int i = 0; i < 16; i += 4) {		
				Shape line = new Line2D.Double(l[i + 0], l[i + 1], l[i + 2], l[i + 3]);
				g2.draw(line);
			}
		}
	}
}
